package com.zoweunion.mechanic.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class HttpClient {

	public static void main(String[] args) {
//		String url = "https://cloud.zoweunion.com/API/System/MSCS/Facility?type=node&";
		StringBuilder str = new StringBuilder();
		String url = "https://cloud.zoweunion.com/API/System/MSCS/Mining/History?";
		String arg = "NodeFullTag=MSCS.ZHYY.JXS.NJDL.17010101664&istree=false&";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String etime = df.format(new Date());
		String time = null;
		try {
			time = "startTime="+ URLEncoder.encode("2019-01-25","utf-8")+"&endTime="+URLEncoder.encode(etime,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		/*SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String stime = df.format(new Date());
		String etime = df.format(new Date());
		String time = "startTime="+stime+"&endTime="+etime;*/
//		str.append(url).append(arg).append(time);
		str.append(url).append(arg);
		str.append(time);
		String interface_account = "ZOWEUNION";
		String unify_account = "e82444a08987594e11a55b29fef55ae42f4df9fa";
//		String opcpath = "opcpath="+"MSCS.CM.XG.Excavator.06T.17010101018";
		//		String appSecret = getAuthorization(url);
		//		System.out.println(appSecret);
//		String result = doGet(url+opcpath,interface_account,unify_account);
//		https://cloud.zoweunion.com/API/System/MSCS/Mining/History?NodeFullTag=MSCS.ZHYY.JXS.NJDL.17010101664&istree=false&startTime=2019-01-24+&endTime=2019-01-31+11%3A29%3A15
		String result = doGet(str.toString(),interface_account,unify_account);
		System.out.println(result);
	}

	public static String doGet(String url, String interface_account, String unify_account) {
		String appSecret = getAuthorization(url, interface_account, unify_account);
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		String result = "";
		try {
			// 通过址默认配置创建一个httpClient实例
			httpClient = HttpClients.createDefault();
			// 创建httpGet远程连接实例
			HttpGet httpGet = new HttpGet(url);

			// 设置请求头信息，鉴权
			httpGet.setHeader("Authorization", appSecret);
			httpGet.setHeader("content-type", "application/x-www-form-urlencoded");
			// 设置配置请求参数
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
					.setConnectionRequestTimeout(35000)// 请求超时时间
					.setSocketTimeout(60000)// 数据读取超时时间
					.build();
			// 为httpGet实例设置配置
			httpGet.setConfig(requestConfig);
			// 执行get请求得到返回对象
			response = httpClient.execute(httpGet);
			// 通过返回对象获取返回数据
			HttpEntity entity = response.getEntity();
			// 通过EntityUtils中的toString方法将结果转换为字符串
			result = EntityUtils.toString(entity, "utf-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}

	public static String doPut(Map<String, Object> params, String url, String interface_account, String unify_account) {
		String appSecret = getPutAuthorization(url, interface_account, unify_account);
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		String result = "";
		try {
			// 通过址默认配置创建一个httpClient实例
			httpClient = HttpClients.createDefault();
			// 构造list集合，往里面丢数据
			List<org.apache.http.NameValuePair> pairs = new ArrayList<>();
			// 创建httpPut远程连接实例
			HttpPut httpPut = new HttpPut(url);

			pairs.add(new BasicNameValuePair("OperateType","2"));
			pairs.add(new BasicNameValuePair("ObjectName", params.get("things_id").toString()));
			pairs.add(new BasicNameValuePair("ObjectTag", params.get("device_name").toString()));
			pairs.add(new BasicNameValuePair("DTUNO", params.get("things_id").toString()));
			pairs.add(new BasicNameValuePair("TempletName", params.get("templet_Name").toString()));
			pairs.add(new BasicNameValuePair("STNO", "1"));
			pairs.add(new BasicNameValuePair("OrganizeNO", "中慧联合"));

			httpPut.setEntity(new UrlEncodedFormEntity(pairs, Charset.forName("UTF-8")));
			// 设置请求头信息，鉴权
			httpPut.setHeader("Authorization", appSecret);
			httpPut.setHeader("content-type", "application/x-www-form-urlencoded");
			// 设置配置请求参数
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
					.setConnectionRequestTimeout(35000)// 请求超时时间
					.setSocketTimeout(60000)// 数据读取超时时间
					.build();
			// 为httpGet实例设置配置
			httpPut.setConfig(requestConfig);
			// 执行get请求得到返回对象
			response = httpClient.execute(httpPut);
			// 通过返回对象获取返回数据
			HttpEntity entity = response.getEntity();
			// 通过EntityUtils中的toString方法将结果转换为字符串
			result = EntityUtils.toString(entity, "utf-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}

	public static String doPost(String url, String interface_account, String unify_account, String phonenum,
			String content) {
		String appSecret = getPostAuthorization(url, interface_account, unify_account);
		org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
		PostMethod method = new PostMethod(url);
		// CloseableHttpClient httpClient = null;
		// CloseableHttpResponse response = null;
		String result = "";
		// String postData = "phonenum="+phonenum+"&content="+content+"";
		try {
			// 通过址默认配置创建一个httpClient实例
			// httpClient = HttpClients.createDefault();
			// 创建httpGet远程连接实例
			// HttpPost httpPost = new HttpPost(url);

//			JSONObject param= new JSONObject();
//			param.put("number", number);
//			param.put("content",content);
//			StringEntity stringEntity = new StringEntity(param.toString());
//			stringEntity.setContentType("application/x-www-form-urlencoded");
//			httpPost.setEntity(stringEntity);
			// 设置请求头信息，鉴权
//			httpPost.setHeader("Authorization", appSecret);
			method.setRequestHeader("Authorization", appSecret);
//			httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
			// method.setRequestHeader("content-type", "application/x-www-form-urlencoded");
			method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=gb2312");
			NameValuePair[] data = { // 提交短信
					// new NameValuePair("account", account), new NameValuePair("password",
					// password), // 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
					// new NameValuePair("password",
					// util.StringUtil.MD5Encode("密码")),
					new NameValuePair("phonenum", phonenum),
					new NameValuePair("content", new String(content.getBytes("gbk"), "utf-8")),
					// new NameValuePair("postData", postData)
			};
			method.setRequestBody(data);
			// 设置配置请求参数
//			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
//					.setConnectionRequestTimeout(35000)// 请求超时时间
//					.setSocketTimeout(60000)// 数据读取超时时间
//					.build();
			// 为httpGet实例设置配置
			// httpPost.setConfig(requestConfig);
			// 执行get请求得到返回对象
			// response = httpClient.execute(method);
			httpClient.executeMethod(method);
			String SubmitResult = method.getResponseBodyAsString();

			// System.out.println(SubmitResult);

			Document doc = DocumentHelper.parseText(SubmitResult);
			Element root = doc.getRootElement();

			String code = root.elementText("code");
			String msg = root.elementText("msg");
			String smsid = root.elementText("smsid");

			if ("2".equals(code)) {
				JSONObject json = new JSONObject();
				json.put("code", code);
				json.put("mobile_code", content);
				return json.toString();
			}
			// 通过返回对象获取返回数据
			// HttpEntity entity = response.getEntity();
			// 通过EntityUtils中的toString方法将结果转换为字符串
			// result = EntityUtils.toString(entity, "utf-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 释放链接
			method.releaseConnection();
			// 关闭HttpClient实例
			if (httpClient != null) {
				((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown();
				httpClient = null;
			}
			// 关闭资源
//			if (null != response) {
//				try {
//					response.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//			if (null != httpClient) {
//				try {
//					httpClient.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
		}

		return result;
	}

	public static String getAuthorization(String url, String interface_account, String unify_account) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		String time = df.format(new Date());
		String str = "TOS username=" + "\"" + interface_account + "\"" + ",uri=" + "\"" + url + "\"" + ",response="
				+ "\"" + MD5.md5(time + ":" + "GET" + ":" + url + ":" + unify_account) + "\"";
		return str;
	}

	public static String getPostAuthorization(String url, String interface_account, String unify_account) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		String time = df.format(new Date());
		String str = "TOS username=" + "\"" + interface_account + "\"" + ",uri=" + "\"" + url + "\"" + ",response="
				+ "\"" + MD5.md5(time + ":" + "POST" + ":" + url + ":" + unify_account) + "\"";
		return str;
	}

	public static String getPutAuthorization(String url, String interface_account, String unify_account) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		String time = df.format(new Date());
		String str = "TOS username=" + "\"" + interface_account + "\"" + ",uri=" + "\"" + url + "\"" + ",response="
				+ "\"" + MD5.md5(time + ":" + "PUT" + ":" + url + ":" + unify_account) + "\"";
		return str;
	}

}
